#!/usr/bin/python
#encoding=utf-8

'''
Created on Apr 8, 2014

@author: root
'''
import uuid
from wm.etc.config import ALARMTYPE
from wm.lib.loglib import log_error
from wm.lib import monitorlib
from wm.lib.websitelib import website_alive_check
from wm.db.TransactionManager import TransactionManager

def website_status_alarm(row):
    try:
        sql = None
        check,result,reason,level = website_alive_check(row[1])
        tran = TransactionManager()
        try:
            tran.startTransaction()
            if check == '1':
                alarmcontent = 'website alive:'+str(result['status'])
                alarmid = uuid.uuid1().__str__().replace("-","") 
                sql = "insert into alarmevent("+\
                             "id,createDate,modifyDate,alertCategory,alertContent,occurrenceDate,"+\
                                    "status,websiteName,websiteConfigInfo_id) "+\
                                    "values('" + alarmid + "'," + " CURRENT_TIMESTAMP()," + " CURRENT_TIMESTAMP()," +\
                                    str(ALARMTYPE['WEBSITE_STATUS_ALARM']) + ",'" + alarmcontent + "'," + "CURRENT_TIMESTAMP()," + str(0) + ",'" + row[2] + "'," +\
                                    "'" + row[0] + "')"                        
                tran.execute(sql)
                monitorlib.update_recent_alarmevent(tran,row[0],row[2],str(ALARMTYPE['WEBSITE_STATUS_ALARM']),alarmcontent)
                
                sql = "insert into websitestatus("+\
                                 "id,createDate,modifyDate,responseCode,websiteStatusType,alarmEvent_id,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 "," + str(1) + "," + str(1) + ",'"+ str(alarmid) + "','" + row[0] + "')"    
            else:
                sql = "insert into websitestatus("+\
                                 "id,createDate,modifyDate,responseCode,websiteStatusType,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 ",'" + str(result['status']) + "'," + str(0) + ",'" + row[0] + "')" 
            tran.execute(sql)
            tran.commitTransaction()
        except:
            tran.rollbackTransaction()
        finally:
            tran.close()
    except Exception as e:
        log_error("website_status_alarm():"+str(e))
